<?php
/**
 * Created by PhpStorm.
 * Author: D H
 * Date: 2017/6/23
 * Time: 10:29
 */
namespace app\api\logic;

use think\Db;
use tool\Common;
use think\Request;

class Topic extends Base {

    //发表话题
    public function publishTopic(){
      //测试数据
        /*$arr = ' {
            "title": "绳索打结的简单方法",
            "content": "原创绳索打结方法，欢迎吃瓜群众围观",
            "imageURL": [
                {
                    "img": "http://menhai.qianchengwl.cn/Uploads/image.jpg"
                },
                {
                    "img": "http://menhai.qianchengwl.cn/Uploads/image.jpg"
                }
            ]
        }';
        $data = json_decode($arr,true);*/
        $data = $this->data;
        //获取用户信息
        //判断同一个用户是否重复发表话题
        $exist = Db::name('topic')->where('title',$data['title'])->where('userID',$this ->getUserID())->find();
        if ($exist){
           return Common::rm(-2,'您已经发表过该话题，请勿重发');
        }
        //添加数据进数据库
        $data['userID'] = $this ->getUserID();
        $data['addtime'] = THINK_START_TIME;
        $data['img'] = json_encode($data['imageURL']);
        unset($data['imageURL']);
        $id = Db::name('topic')->insertGetId($data);
        return Common::rm(1,'操作成功',['topicID' => $id]);
    }

    //得到最新话题（所有话题）
    public function getNewTopic(){
        $data = $this->data;
        $list = Db::view('topic',['id' => 'topicID','content','title','praise','img','userID','past'])
            ->view('operator',['name' => 'userName','photo'],'topic.userID = operator.id')
            ->limit(($data['startPoint'] - 1) * 5, 5)
            ->order('addtime desc')
            ->select();
        if (!$list){
            return Common::rm(-3,'没有任何动态');
        }
        foreach ($list as $k => $val){
            $list[$k]['imgURL'] = json_decode($val['img'],true);
            unset($list[$k]['img']);
            //判断是否点赞
            if ($val['past']){
             $a = explode(',',$val['past']);
             foreach ($a as $key => $value){
                 if ($value == $this->getUserID()){
                     $list[$k]['past'] =1;
                 }else{
                     $list[$k]['past'] = 0;
                 }
             }
            }else{
                $list[$k]['past'] =0;
            }
        }

        return Common::rm(1,'操作成功',['topicList' => $list]);
    }

    //根据话题ID得到话题详细内容
    public function getDetailsByTopicID(){
        //测试数据
        /*$arr = ' {
           "topicID": 2
        }';
        $data = json_decode($arr,true);*/
        $data = $this->data;
        $new_arr = Db::view('topic',['content','title','addtime','praise','img' => 'imgURL','pastc'])
            ->view('operator',['id' => 'userID','name' => 'userName','photo'],'operator.id = topic.userID')
            ->where('topic.id',$data['topicID'])
            ->find();

        $new_arr['imgURL'] = json_decode($new_arr['imgURL'],true);
        $new_arr['addtime'] = date('Y-m-d H:i:s',$new_arr['addtime']);
        //回答
        $answer = Db::view('topic_answer',['content','addtime','praise'])
            ->view('operator',['id' => 'userID','name' => 'userName','photo'],'topic_answer.userID = operator.id')
            ->where('parentID',0)
            ->where('topicID',$data['topicID'])
            ->limit(2)
            ->order('addtime')
            ->select();
        //回答数量
        $num = Db::name('topic_answer')->where('topicID',$data['topicID'])->select();
        foreach ($answer as $k => $val){
            $answer[$k]['addtime'] = date('Y-m-d',$val['addtime']);
        }
        if ($new_arr['pastc']){
            $a = explode(',',$new_arr['pastc']);
            foreach ($a as $key => $value){
                if ($value == $this->getUserID()){
                    $new_arr['past'] =1;
                }else{
                    $new_arr['past'] = 0;
                }
            }
        }else{
            $new_arr['pastc'] = 0;
        }
        if ($num){
            $new_arr['total'] = count($num);      //评论总数
           // $new_arr['exist'] = 1;
        }else{
            $new_arr['total'] = 0;
           // $new_arr['exist'] = 0;
        }

        if ($answer){
            $new_arr['answer'] = $answer;
        }else{
            $new_arr['answer'] = [];
        }

        return Common::rm(1,'操作成功',$new_arr);
    }

    //话题回复
    public function replyTopic(){
        //测试数据
        $data = $this->data;
        $new_data = [
            'topicID' => $data['topicID'],
            'userID' => $this ->getUserID(),
            'content' => $data['content'],
            'parentID' =>  $data['contentID'],
            'sendUserID' => $data['sendUserID'],
            'addtime' => THINK_START_TIME
        ];
         // 添加数据
        $id = Db::name('topic_answer')->insertGetId($new_data);
        //判断是否有人回答该问题
        Db::name('topic')->where('id',$data['topicID'])->update(['status' =>1]);
        if ($id){
            return Common::rm(1,'操作成功');
        }

    }


    //根据话题ID得到评论
    public function getCommentsByTopicID(){
        //得到新闻评论(10条)
        $userID = $this->getUserID();
        $list = Db::view('topic_answer',['id' => 'contentID','content','addtime','praise','past'])
            ->view('operator',['id' => 'userID','name' => 'userName','thumb'],'operator  .id = topic_answer.userID')
            ->where('topic_answer.topicID',$this->data['topicID'])
            ->where('parentID',0)
            ->limit(10)
            ->order('addtime desc')
            ->select();
        $result = [];
        if ($list){
            foreach ($list as $k => $val){
                $result[$k]['userID'] = $val['userID'];
                $result[$k]['name'] = $val['userName'];
                $result[$k]['content'] = $val['content'];
                $result[$k]['contentID'] = $val['contentID'];
                $result[$k]['praise'] = $val['praise'];
                $result[$k]['thumb'] = $val['thumb'];
                $result[$k]['addtime'] = date('Y-m-d H:i',$val['addtime']);
                if (!empty($val['past'])){
                    //用户已经对该评论点赞
                    $a = explode(',',$val['past']);
                    foreach ($a as $key => $value){
                        if ($value == $userID){
                            $result[$k]['past'] = 1;
                            break;
                        }else{
                            $result[$k]['past'] = 0;
                        }
                    }
                }else{
                    //用户未对该评论点赞
                    $result[$k]['past'] = 0;
                }
            }
            return Common::rm(1,'操作成功',['commentsList' => array_reverse($result)]);
        }else{
            return Common::rm(-2,'客官暂时还没有任何评论哟');
        }
    }


    //话题点赞
    public function thumbUpTopic(){
        $data = $this->data;
        $exist = Db::name('topic')->where('id',$data['topicID'])->find();
        if (!empty($exist['past'])){
            //用户已经对该评论点赞
            $a = explode(',',$exist['past']);
            foreach ($a as $key => $value){
                if ($value == $this->getUserID()){
                    return Common::rm(-2,'请不要重复点赞');
                }else{
                    $praise = [
                        'praise' => $exist['praise'] +1,
                        'past' => $exist['past'].','.$this->getUserID()
                    ];
                    Db::name('topic')->where('id',$data['topicID'])->update($praise);
                }
            }
        }else{
            $praise = [
                'praise' => $exist['praise'] +1,
                'past' =>$this->getUserID()
            ];
            Db::name('topic')->where('id',$data['topicID'])->update($praise);
        }

        return Common::rm(1,'操作成功');
    }


    //取消话题点赞
    public function cancelThumbUp(){
        $data = $this->data;
        $num = DB::view('topic','praise,past')->where('id',$data['topicID'])->find();
        if (!$num){
            return Common::rm(-2,'操作失败');
        }
        $a = explode(',',$num['past']);
        foreach ($a as $k => $val){
            if ($val == $this->getUserID()){
                unset($a[$k]);
            }
        }
        $praise = [
            'praise' => $num['praise'] -1,
            'past' =>implode(',',$a)
        ];
        Db::name('topic')->where('id',$data['topicID'])->update($praise);
        return Common::rm(1,'操作成功');
    }


    //删除话题
    public function deleteTopic(){
        //测试数据
        /*$arr = ' {
          "topicID": 4
        }';
        $data = json_decode($arr,true);*/
        $data = $this->data;
       // $user = ['userID' => 3];
        Db::name('topic')->where('id',$data['topicID'])->where('userID',$this->getUserID())->delete();
         return Common::rm(1,'操作成功');
    }

    //与我相关
    /*public function relatedForMe()
    {
        $userID = $this->getUserID();
        $topicID = Db::name('topic_answer')->where('userID',$userID)->whereOr('sendUserID',$userID)->distinct('topicID')->column('topicID');
        if (!$topicID) {
            return Common::rm(-3,'数据为空');
        }
        $answer = Db::view('topic_answer','id,parentID,topicID,addtime,content')
            ->view('topic','title','topic.id = topic_answer.topicID')
            ->view('operator',['name' => 'authorName'],'operator.id = topic.userID')
            ->view(['a_operator' => 'newuser'],'name,photo','newuser.id = topic_answer.userID')
            ->where('topicID','in',$topicID)
            ->where('sendUserID',0)
            ->order('addtime desc')
            ->select();
        $newAnswer = [];
        foreach ($answer as $key => $val) {
            $newAnswer[$val['topicID']][] = $val;
        }
        $newAr = [];
        foreach ($newAnswer as $_key => $_val) {
            
            foreach ($_val as $__key => $__val) {
                dump($__val);exit;
            }
        }
        dump($newAnswer);exit;
        $answer1 = Db::view('topic_answer','id,parentID,topicID,addtime,content')
            ->view('topic','title','topic.id = topic_answer.topicID')
            ->view(['a_operator' => 'newuser1'],['name' => 'authorName'],'newuser1.id = topic.userID')
            ->view('operator','name,photo','operator.id = topic_answer.userID')
            ->view(['a_operator'=>'newuser'],['name' => 'sendName','photo' => 'sendPhoto'],'newuser.id = topic_answer.sendUserID')
            ->where('topicID','in',$topicID)
            ->order('addtime desc')
            ->select();
        $sendAnswer = Db::name('topic_answer')->where('topicID','in',$topicID)->field('id,content')->select();
        foreach ($answer1 as $_key => $_val) {
            foreach ($sendAnswer as $__key => $__val) {
                if ($_val['parentID'] == $__val['id']) {
                    $answer1[$_key]['sendContent'] = $__val['content'];
                }
            }
        }
        foreach ($answer1 as $key => $val) {
            array_push($answer,$val);
        }
        $ar = [];
        foreach ($answer as $k => $v) {
            $answer[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            $ar[]  = $v['addtime'];
        }
        array_multisort($ar,SORT_DESC,$answer);
        dump($answer);exit;
    }*/

    //论坛与我相关
    public function relatedForMe()
    {
        $userID = $this->getUserID();
        $topicID = Db::name('topic_answer')->where('userID',$userID)->whereOr('sendUserID',$userID)->distinct(true)->column('topicID');
        if (!$topicID) {
            return Common::rm(-3,'数据为空');
        }
        $answer = Db::view('topic_answer',['id' => 'answerID','userID','parentID','userID','sendUserID','topicID','addtime','content'])
            ->view('topic','title','topic.id = topic_answer.topicID')
            ->view('operator',['name' => 'authorName'],'operator.id = topic.userID')
            ->view(['a_operator' => 'newuser'],'name,photo','newuser.id = topic_answer.userID')
            ->where('topicID','in',$topicID)
            ->where('sendUserID',0)
            ->order('addtime desc')
            ->select();
        $newAnswer = [];
        foreach ($answer as $key => $val) {
            $newAnswer[$val['topicID']][] = $val;
        }
        $newAr = [];
        foreach ($newAnswer as $_key => $_val) {
            $newAr[$_key]['topicID'] = $_val[0]['topicID'];
            $newAr[$_key]['parentID'] = $_val[0]['parentID'];
            $newAr[$_key]['title'] = $_val[0]['title'];
            $newAr[$_key]['authorName'] = $_val[0]['authorName'];
            foreach ($_val as $__key => $__val) {
                $newAr[$_key]['comment'][$__key]['answerID'] = $__val['answerID'];
                $newAr[$_key]['comment'][$__key]['userID'] = $__val['userID'];
                $newAr[$_key]['comment'][$__key]['name'] = $__val['name'];
                $newAr[$_key]['comment'][$__key]['photo'] = $__val['photo'];
                $newAr[$_key]['comment'][$__key]['content'] = $__val['content'];
                $newAr[$_key]['comment'][$__key]['addtime'] = date('Y-m-d H:i:s',$__val['addtime']);
            }
        }
        $answer = array_reverse($newAr);
        $answer1 = Db::view('topic_answer',['id' => 'answerID','userID','parentID','userID','sendUserID','topicID','addtime','content'])
            ->view('topic','title','topic.id = topic_answer.topicID')
            ->view(['a_operator' => 'newuser1'],['name' => 'authorName'],'newuser1.id = topic.userID')
            ->view('operator','name,photo','operator.id = topic_answer.userID')
            ->view(['a_operator'=>'newuser'],['name' => 'sendName','photo' => 'sendPhoto'],'newuser.id = topic_answer.sendUserID')
            ->where('topicID','in',$topicID)
            ->order('addtime')
            ->select();
        $sendAnswer = Db::name('topic_answer')->where('topicID','in',$topicID)->field('id,content')->select();
        foreach ($answer1 as $_key => $_val) {
            foreach ($sendAnswer as $__key => $__val) {
                if ($_val['parentID'] == $__val['id']) {
                    $answer1[$_key]['sendContent'] = $__val['content'];
                    $answer1[$_key]['addtime'] = date('Y-m-d H:i:s',$_val['addtime']);
                }
            }
        }
        foreach ($answer1 as $key => $val) {
            array_unshift($answer,$val);
        }
        /*$count = $this->data['count'];
        if ($this->data['page'] == 1) {
            $page = 0;
        } else {
            $page = ($this->data['page'] - 1) * $count;
        }
        $answer = array_slice($answer, $page, $count);*/
        return Common::rm(1,'操作成功',[
            'topic' => $answer
        ]);
    }

    //未回答话题
    public function notAnswer(){
        $data = $this->data;
        $list = Db::view('topic','content,title,praise,img,userID,past')
            ->view('operator',['name' => 'userName','photo'],'topic.userID = operator.id')
            ->limit(($data['startPoint'] - 1) * 5, 5)
            ->where('status',0)
            ->order('addtime desc')
            ->select();
        if (!$list){
            return Common::rm(-3,'没有数据');
        }
        foreach ($list as $k => $val){
            $list[$k]['imgURL'] = json_decode($val['img'],true);
            unset($list[$k]['img']);
            if ($val['past']){
                $a = explode(',',$val['past']);
                foreach ($a as $key => $value){
                    if ($value == $this->getUserID()){
                        $list[$k]['past'] =0;
                    }else{
                        $list[$k]['past'] = 1;
                    }
                }
            }else{
                $list[$k]['past'] =0;
            }
        }
        return Common::rm(1,'操作成功',['topicList' => $list]);
    }

}